package com.dinzeer.legendreliclib.lib.compat.slashblade;

import mods.flammpfeil.slashblade.SlashBlade;
import mods.flammpfeil.slashblade.capability.concentrationrank.ConcentrationRankCapabilityProvider;
import mods.flammpfeil.slashblade.entity.EntityDrive;
import mods.flammpfeil.slashblade.item.ItemSlashBlade;
import mods.flammpfeil.slashblade.util.VectorHelper;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.phys.Vec3;

import java.util.Random;

public class Drives {


    /**
     * 在玩家周围生成圆形分布的剑气实体
     * 
     * @param playerIn 作为剑气发射源的玩家实体
     * @param numPoints 要生成的剑气数量
     * @param damage 剑气伤害值
     */
    public static void spawnCircularDrives(LivingEntity playerIn, int numPoints, float damage,float roll,float lifetime) {
        Vec3 centerOffset =Vec3.ZERO;
        int colorCode =
                (Integer)playerIn.getMainHandItem().getCapability(ItemSlashBlade.BLADESTATE)
                        .map((state) -> state.getColorCode()).orElse(-13421569);

        // 获取玩家视角方向和位置
        Vec3 lookAngle = playerIn.getLookAngle();
        Vec3 pos = playerIn.position().add(0.0F, playerIn.getEyeHeight() * 0.75F, 0.0F).add(lookAngle.scale(0.3F));
        for (int i = 0; i < numPoints; i++) {
            // 计算当前点在圆上的角度
            double angleDeg = (360.0 / numPoints) * i;
            double angleRad = Math.toRadians(angleDeg);

            // 计算该点在水平面上的偏移量
            double offsetX = Math.cos(angleRad);
            double offsetZ = Math.sin(angleRad);

            // 创建新的剑气实体 (修复多个实体使用同一个实例的问题)
            EntityDrive drive = new EntityDrive(SlashBlade.RegistryEvents.Drive, playerIn.level());
            drive.setPos(pos.x, pos.y, pos.z);
            DriveBaseSet(drive, damage/numPoints, playerIn, colorCode,roll,lifetime);
            
            // 设置剑气方向
            Vec3 driveDirection = new Vec3(offsetX, 0, offsetZ).normalize();
            drive.shoot(driveDirection.x, driveDirection.y, driveDirection.z, drive.getSpeed(), 0.0F);
            
            setConcentrationRank(drive, playerIn);
            playerIn.level().addFreshEntity(drive);
        }
    }
    
    /**
     * 向玩家视角正前方发射剑气
     * 
     * @param playerIn 玩家实体
     * @param damage 剑气伤害值
     * @param count 发射数量
     * @param roll 角度
     * @param lifetime 存活时间
     */
    public static void spawnForwardDrive(LivingEntity playerIn, float damage, int count,float roll,float lifetime) {
        int colorCode = getColorCode(playerIn);
        Vec3 lookAngle = playerIn.getLookAngle();
        Vec3 pos = calculatePosition(playerIn, lookAngle);
        
        for (int i = 0; i < count; i++) {
            EntityDrive drive = new EntityDrive(SlashBlade.RegistryEvents.Drive, playerIn.level());
            drive.setPos(pos.x, pos.y, pos.z);
            DriveBaseSet(drive, damage, playerIn, colorCode,roll,lifetime);
            
            // 设置正前方方向
            drive.shoot(lookAngle.x, lookAngle.y, lookAngle.z, drive.getSpeed(), 0.0F);
            
            setConcentrationRank(drive, playerIn);
            playerIn.level().addFreshEntity(drive);
        }
    }






    /**
     * 向发射剑气
     *
     * @param playerIn 玩家实体
     * @param pos 剑气的pos
     * @param angleOffset 偏移角度
     * @param damage 剑气伤害值
     * @param roll 剑气旋转角度
     */
    public static void shootDrive(LivingEntity playerIn, Vec3 pos, float angleOffset,float damage,float roll) {
        EntityDrive drive = new EntityDrive(SlashBlade.RegistryEvents.Drive, playerIn.level());
        playerIn.level().addFreshEntity(drive);

        float speed = Mth.randomBetween(drive.level().getRandom(), 2F, 5F);
        drive.setPos(pos.x, pos.y, pos.z);
        drive.setDamage(damage);
        drive.setSpeed(speed);

        float yaw = playerIn.getViewYRot(1.0F) + angleOffset; // 使用更平滑的插值Yaw
        Vec3 direction = VectorHelper.getVectorForRotation(0, yaw); // 水平旋转

        drive.shoot(direction.x, direction.y, direction.z, drive.getSpeed(), 0);

        drive.setOwner(playerIn);
        drive.setRotationRoll(roll);

        int colorcode = playerIn.getMainHandItem()
                .getCapability(ItemSlashBlade.BLADESTATE)
                .map(state -> state.getColorCode()).orElse(0xFF3333FF);
        drive.setColor(colorcode);
        drive.setIsCritical(true);
        drive.setLifetime(30);

        if (playerIn != null)
            playerIn.getCapability(ConcentrationRankCapabilityProvider.RANK_POINT)
                    .ifPresent(rank -> drive.setRank(rank.getRankLevel(playerIn.level().getGameTime())));
    }





    /**
     * 随机散射型剑气
     * 
     * @param playerIn 玩家实体
     * @param numPoints 散射数量
     * @param damage 剑气伤害值
     */
    public static void spawnScatteredDrives(LivingEntity playerIn, int numPoints, float damage,float roll,float lifetime) {
        int colorCode = getColorCode(playerIn);
        Vec3 lookAngle = playerIn.getLookAngle();
        Vec3 pos = calculatePosition(playerIn, lookAngle);
        
        Random random = new Random();
        for (int i = 0; i < numPoints; i++) {
            EntityDrive drive = new EntityDrive(SlashBlade.RegistryEvents.Drive, playerIn.level());
            drive.setPos(pos.x, pos.y, pos.z);
            DriveBaseSet(drive, damage, playerIn, colorCode,roll,lifetime);
            
            // 随机方向向量 (水平±45度，垂直±15度)
            double yaw = (random.nextDouble() - 0.5) * Math.PI/2; 
            double pitch = (random.nextDouble() - 0.5) * Math.PI/6;
            Vec3 randomDir = new Vec3(
                Math.sin(yaw) * Math.cos(pitch),
                Math.sin(pitch),
                Math.cos(yaw) * Math.cos(pitch)
            ).normalize();
            
            drive.shoot(randomDir.x, randomDir.y, randomDir.z, drive.getSpeed(), 0.0F);
            
            setConcentrationRank(drive, playerIn);
            playerIn.level().addFreshEntity(drive);
        }
    }
    
    // 提取公共方法：计算位置
    private static Vec3 calculatePosition(LivingEntity playerIn, Vec3 lookAngle) {
        return playerIn.position()
            .add(0.0F, playerIn.getEyeHeight() * 0.75F, 0.0F)
            .add(lookAngle.scale(0.3F));
    }
    
    // 提取公共方法：获取颜色代码
    private static int getColorCode(LivingEntity playerIn) {
        return (Integer)playerIn.getMainHandItem().getCapability(ItemSlashBlade.BLADESTATE)
            .map((state) -> state.getColorCode()).orElse(-13421569);
    }
    
    // 提取公共方法：设置集中度等级
    private static void setConcentrationRank(EntityDrive drive, LivingEntity playerIn) {
        if (playerIn != null) {
            playerIn.getCapability(ConcentrationRankCapabilityProvider.RANK_POINT).ifPresent((rank) ->
                drive.setRank(rank.getRankLevel(playerIn.level().getGameTime())));
        }
    }

    public static void DriveBaseSet(EntityDrive drive,float damage,LivingEntity playerIn,int colorCode,float roll,float lifetime){
        drive.setDamage(damage);
        drive.setSpeed(2f);
        drive.setOwner(playerIn);
        drive.setRotationRoll(roll);
        drive.setColor(colorCode);
        drive.setLifetime(lifetime);
    }

}
